package BLC

import (
	"flag"
	"fmt"
	"log"
	"os"
)

type CLI struct {}

func printUseage()  {

	fmt.Println("Usage:")
	fmt.Println("\tcreateblockchain -address -- 交易数据...")
	fmt.Println("\tsend -from From -to TO -amount AMOUNT -- 交易明细..")
	fmt.Println("\tprintchain -- 输入区块信息.")
}

// 判断参数是否合法
func isValidArgs()  {
	if len(os.Args) < 2 {
		printUseage()
		os.Exit(1)

	}
}

// 命令行添加区块
func (cli *CLI) addBlock(txs []*Transaction)  {

	if DBExists() == false{
		fmt.Println("数据不存在")
		os.Exit(1)
	}

	blockchain := BlockchainObject()

	defer blockchain.DB.Close()

	blockchain.AddBlockToBlockchain(txs)


}

func (cli *CLI) printchain()  {
	if DBExists() == false{
		fmt.Println("数据不存在")
		os.Exit(1)
	}

	blockchain := BlockchainObject()

	defer blockchain.DB.Close()
	blockchain.Printchain()
}

func (cli *CLI) createGenesisBlockchain(address string)  {

	CreateBlockchainWithGenesisBlock(address)
}

func (cli *CLI) Run()  {
	isValidArgs()

	sendBlockCmd := flag.NewFlagSet("send",flag.ExitOnError)
	printChainCmd := flag.NewFlagSet("printchain",flag.ExitOnError)
	createBlockchainCmd := flag.NewFlagSet("createblockchain",flag.ExitOnError)

	flagFrom := sendBlockCmd.String("from","","转账源地址")
	flagTo := sendBlockCmd.String("to","","转账目的地址")
	flagAmount := sendBlockCmd.String("amount","","转账金额")


	flagCreateBlockchainWithData := createBlockchainCmd.String("address","创世区块创建","创世区快数据")

	switch os.Args[1] {
	case "send":
		err := sendBlockCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	case "printchain":
		err := printChainCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	case "createblockchain":
		err := createBlockchainCmd.Parse(os.Args[2:])
		if err != nil {
			log.Panic(err)
		}
	default:
		printUseage()
		os.Exit(1)
	}

	if sendBlockCmd.Parsed(){
		if *flagFrom == ""|| *flagTo == ""||*flagAmount == ""{
			printUseage()
			os.Exit(1)
		}

		//cli.addBlock([]*Transaction{})
		fmt.Println(*flagFrom)
		fmt.Println(*flagTo)
		fmt.Println(*flagAmount)
	}

	if printChainCmd.Parsed(){
		cli.printchain()
	}

	if createBlockchainCmd.Parsed(){
		if *flagCreateBlockchainWithData == "" {
			fmt.Println("地址不能为空....")
			printUseage()
			os.Exit(1)

		}

		cli.createGenesisBlockchain(*flagCreateBlockchainWithData)
	}



}
